//
//  PersonalViewController.swift
//  HiBook
//
//  Created by Apple on 16/8/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import WebKit
import ImagePicker


class PersonalViewController: UIViewController,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,PhotoPickerFunctions {
    var moreWebView : WKWebView?
    
    var action:String?
    
    let obj = AVObject(className: "new")


    override func viewDidLoad() {
        super.viewDidLoad()

        
        let config = WKWebViewConfiguration()
        
        self.moreWebView = WKWebView(frame: self.view.frame ,configuration: config)
        
        self.moreWebView?.UIDelegate = self
        
        self.moreWebView?.navigationDelegate = self
        
        self.moreWebView?.configuration.userContentController.addScriptMessageHandler(self, name: "responesToPhone")
        
        self.moreWebView?.allowsBackForwardNavigationGestures = true
        
        self.moreWebView?.scrollView.scrollEnabled = false
        
        let request = NSURLRequest(URL: NSURL(string: "http://\(MAIN_IP):8000/web/personal.html")!)
        
        self.moreWebView?.loadRequest(request)
        
        self.view.addSubview(moreWebView!)
        //加上navbar
        let navbar = UINavigationBar(frame: CGRectMake(0,0,SCREEN_WIDTH,55))
        navbar.barTintColor = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1)
        navbar.tintColor = UIColor(red: 87/255, green: 191/255, blue: 294/255, alpha: 1)
        
        let navtitle = UINavigationItem(title: "个人中心")
        navtitle.titleView?.tintColor = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1)
        navbar.pushNavigationItem(navtitle, animated: false)
        
        let navCancel = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(self.cancelBtn))
        let navConfirm = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(self.confirmBtn))
        
        navtitle.leftBarButtonItem = navCancel
        navtitle.rightBarButtonItem = navConfirm
        
//        UINavigationBar.setItems([navbar])
        
        
        self.view.addSubview(navbar)
    }
    
    func cancelBtn(){
        self.dismissViewControllerAnimated(true) { 
            self.obj.deleteInBackground()
        }
    }
    func confirmBtn(){
        self.dismissViewControllerAnimated(true) {
            self.obj.deleteInBackground()
        }
    }

    func responesToPhone(action:String ){
        let pickVC = PhotoPickerViewController()
        print(self)
        switch action {
        case "camera":
            pickVC.delegate = self
            self.presentViewController(pickVC, animated: true) {

            }

        case "dismiss":
            noticeSuccess("保存成功", autoClear: true, autoClearTime: 1)

            self.dismissViewControllerAnimated(true, completion: {
                
            })

        default:
            print("位置情况")
        }
        

        
    }
    
    func getImageFromPicker(image: UIImage) {
        
//        let height = CGFloat(50)
//        let width = CGFloat(50)
//        
//        let imageWatingCrop = image
//        let cgImageWatingCrop = imageWatingCrop.CGImage
//        let imageRef = CGImageCreateWithImageInRect(cgImageWatingCrop, CGRectMake(0, 0, width, height))
//        //release
//        let imageCropped = UIImage(CGImage: imageRef!)
//        
//        
        let imageData = UIImageJPEGRepresentation(image, 0.1)
        let file = AVFile(name: "a.jpg", data: imageData)

        print(imageData)
        file.saveInBackgroundWithBlock { (success, error) in
            if success {

                self.noticeSuccess("成功", autoClear: true, autoClearTime: 1)
                let id = file.objectId
                
                let query = AVQuery(className: "_File")
                query.getObjectInBackgroundWithId(id) { (o, e) in
                    print(o.valueForKey("url") as! String)
                    
                    self.obj.setObject(o.valueForKey("url") as! String, forKey: "url")
                    self.obj.save()
                    
                    
                    self.moreWebView?.evaluateJavaScript("change()", completionHandler: { (o, e) in
                        if e != nil {
                            print(e)
                        }
                        print(o)
                        self.moreWebView?.reload()

                    })
                    self.moreWebView?.reload()
                    
                }

            }else{
                print(error)
            }
            

        }
        

    }
    
    
    func htmlForJPGImage(image : UIImage) -> String{
        
        
        let imageData = UIImageJPEGRepresentation(image, 1)
        
        
        let imageString = "\(imageData!)"
        //去掉尖括号
        let t1 = imageString.stringByReplacingOccurrencesOfString("<", withString: "")
        let newImageString = t1.stringByReplacingOccurrencesOfString(">", withString: "")
        
        let imageSource = "data:image/jpg;base64,\(newImageString)"
        
        let imageSourceFinally = "\(imageSource)"
        
        return "<img src = \(imageSourceFinally) />"
    }
    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        NSLog("方法名:\(message.name) 传回:\(message.body)")
        
        self.action = message.body as? String
        
        self.responesToPhone(action!)
    }
    func webViewDidStartLoad(webView: UIWebView) {
        NSLog("启动")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        NSLog("结束")
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        NSLog("error:\(error)")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
